package cn.smbms.controller;

import cn.smbms.pojo.Role;
import cn.smbms.pojo.User;
import cn.smbms.service.role.RoleService;
import cn.smbms.service.role.RoleServiceImpl;
import cn.smbms.service.user.UserService;
import cn.smbms.service.user.UserServiceImpl;
import cn.smbms.tools.Constants;
import cn.smbms.tools.PageSupport;
import com.alibaba.fastjson.JSON;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Controller
@RequestMapping("/user")
public class UserController{
    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;
    @RequestMapping("/login")
    public String login(String userCode, String userPassword,
                        HttpSession session, Model model){
        System.out.println("login ============ " );
        //获取用户名和密码
//        String userCode = request.getParameter("userCode");
//        String userPassword = request.getParameter("userPassword");
        //调用service方法，进行用户匹配
   //     UserService userService = new UserServiceImpl();
        User user = userService.login(userCode,userPassword);
        if(null != user){//登录成功
            //放入session
           session.setAttribute(Constants.USER_SESSION, user);
            //页面跳转（frame.jsp）
            //response.sendRedirect("jsp/frame.jsp");
            return "frame";
        }else{
            //页面跳转（login.jsp）带出提示信息--转发
            model.addAttribute("error", "用户名或密码不正确");
            throw  new RuntimeException("用户名或密码错误");
        }

    }
    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute(Constants.USER_SESSION);
        return "login";
    }
    @RequestMapping("/list")
    public String list(String queryname,
                       Integer queryUserRole,
                       Integer pageIndex,HttpServletRequest request){
        List<User> userList = null;
        //设置页面容量
        int pageSize = Constants.pageSize;
        //当前页码
        int currentPageNo = 1;
        System.out.println("queryUserName servlet--------"+queryname);
        System.out.println("queryUserRole servlet--------"+queryUserRole);
        System.out.println("query pageIndex--------- > " + pageIndex);
        if(queryname == null){
            queryname = "";
        }
        if(null==queryUserRole){
            queryUserRole=0;
        }

        if(pageIndex != null){
            currentPageNo = pageIndex;
        }
        //总数量（表）
        int totalCount	= userService.getUserCount(queryname,queryUserRole);
        //总页数
        PageSupport pages=new PageSupport();
        pages.setCurrentPageNo(currentPageNo);
        pages.setPageSize(pageSize);
        pages.setTotalCount(totalCount);

        int totalPageCount = pages.getTotalPageCount();

        //控制首页和尾页
        if(currentPageNo < 1){
            currentPageNo = 1;
        }else if(currentPageNo > totalPageCount){
            currentPageNo = totalPageCount;
        }
        userList = userService.getUserList(queryname,queryUserRole,currentPageNo, pageSize);
        request.setAttribute("userList", userList);
        List<Role> roleList = null;
       // RoleService roleService = new RoleServiceImpl();
        roleList = roleService.getRoleList();
        request.setAttribute("roleList", roleList);
        //查询的条件传回去，实现了条件回显
        request.setAttribute("queryUserName", queryname);
        request.setAttribute("queryUserRole", queryUserRole);
        request.setAttribute("totalPageCount", totalPageCount);
        request.setAttribute("totalCount", totalCount);
        request.setAttribute("currentPageNo", currentPageNo);
        return "userlist";
    }
    @GetMapping("/sys/toadd")
    public String toAdd(){
        return "useradd";
    }
    @PostMapping("/add")
    public String add(User user,
                      HttpServletRequest request,MultipartFile[] attachs){//controller中处理参数的时候可以封装成对象，要求：参数的名称要和对象的属性保持一致
       //1、需要将文件的路径保存到数据库中，定义一个变量
        String idPicPath="";
        String workpicPath="";
        //2、准备工作：a、定义文件上传的路径，
        String path=request.getSession().getServletContext().
                getRealPath("statics"+ File.separator+"uploadFiles");
        // b、上传之前：判断有没有文件要上传，判断文件的大小，类型是否符合规范
        for (int i = 0; i <attachs.length ; i++) {
            MultipartFile attach=attachs[i];
            if(!attach.isEmpty()){
                //获取源文件名
                String oldName=attach.getOriginalFilename();
                //获取源文件后缀
                String suffix= FilenameUtils.getExtension(oldName);
                if(attach.getSize()>500000){//文件大小是否符合
                    request.setAttribute("uploadFileError","文件不得超过500KB");
                    return "useradd";
                }else if(suffix.equalsIgnoreCase("jpg")||
                        suffix.equalsIgnoreCase("jpeg")||
                        suffix.equalsIgnoreCase("png")||
                        suffix.equalsIgnoreCase("pneg")){//文件的类型是否合规
                    //c、修改文件的名称，防止在服务器存在同名覆盖问题
                    String fileName=System.currentTimeMillis()+ RandomUtils.nextInt(1000000)+"."+suffix;
                    File file=new File(path);
                    if(!file.exists()){
                        file.mkdirs();
                    }
                    //3、上传
                    try {
                        attach.transferTo(new File(file,fileName));
                    } catch (IOException e) {
                        e.printStackTrace();
                        request.setAttribute("uploadFileError","文件失败");
                        return "useradd";
                    }
                    if(i==0){
                        idPicPath=File.separator+path+File.separator+fileName;
                    }else if(i==1){
                        workpicPath=File.separator+path+File.separator+fileName;
                    }
                    System.out.println(idPicPath);
                }else{
                    request.setAttribute("uploadFileError","文件格式不正确");
                    return "useradd";
                }
            }
        }
        user.setIdPicPath(idPicPath);
        user.setWorkPicPath(workpicPath);
        user.setCreationDate(new Date());
        user.setCreatedBy(((User)request.getSession().getAttribute(Constants.USER_SESSION)).getId());
        if(userService.add(user)){
            //重定向
            return "redirect:/user/list";
        }else{
            //默认的方式就是转发,服务器实现跳转
            return "useradd";
        }

}
    @RequestMapping("/view/{uid}")
    @ResponseBody
    public User view(@PathVariable  String uid){
        User user=userService.getUserById(uid);
        //String json= JSON.toJSONString(user);
        return user;
    }
    @RequestMapping("/tomodify/{uid}")
    public String tomodify(@PathVariable  String uid,Model model){
        User user=userService.getUserById(uid);
        model.addAttribute("user",user);
        return "usermodify";
    }
    @RequestMapping("/modify")
    public String modify(User user,HttpServletRequest request){
        user.setModifyDate(new Date());
        user.setModifyBy(((User)request.getSession().getAttribute(Constants.USER_SESSION)).getId());
        if(userService.modify(user)){
            return "redirect:/user/list";
        }else{
            return "usermodify";
        }
    }
    @RequestMapping("/ucexist")
    @ResponseBody //将响应的数据写入HTTP Response Body
    public Object ucexist(String userCode){
       User user= userService.selectUserCodeExist(userCode);
       if(null!=user){
           return "exist";
       }else{
           return "noexist";
       }
    }



}
